<?php

namespace app\home\controller;

use think\Controller;
use think\facade\Request;
use app\home\model\User;
use think\facade\Session;

class Login extends Controller
{
    public function register(){
        $this->view->engine->layout(false);
        return view();
    }
    public function login(){
        $this->view->engine->layout(false);
        return view();
    }
    public function phone(){
        //接受数据  
        //检测数据  
        //注册用户(添加)  
        //返回数据（前后台分离  json数据）
        //页面跳转
        $param=Request::param();
        // dump($param);
        $validate=$this->validate($param,[
            'phone|手机号'=>'require|reg:1[3-9]\d{9}|unique:user,phone',
            'code|验证码'=>'require|length:4',
            'password|密码'=>'require|length:6,20|confirm:repassword',
        ]);
        if($validate!==true){
            $this->error($validate);
        }
        //验证验证码
        $code=cache('register_code_'.$param['phone']);
        if($code!=$param['code']){
            $this->error('验证码错误');
        }
        User::create($param,true);
        $this->redirect('login/login');
    }
    //发生验证码
    public function sendCode(){
        //接受参数
        $param=input();
        //检测参数
        //生产验证码
        $code=mt_rand(1000,9999);
        $content="你的注册验证码是{$code}";
        //保存验证码
        cache('register_code_'.$param['phone'],$code);
        //发生验证码
        $res=['code'=>200,'msg'=>"短信发生成功",'data'=>$content];
        json($res)->send();
    }
    public function tologin(){
        $param=input();
        // dump($param);
        $validate=$this->validate($param,[
            'username|用户名'=>'require',
            'password|密码'=>'require|length:6,20',
        ]);
        if($validate!==true){
            $this->error($validate);
        }
        // 方法一
        $res=User::where(function($query) use($param){
            $query->where('username',$param['username'])->whereOr('phone',$param['username'])
            ->whereOr('email',$param['username']);
        })->where('password',$param['password'])->find();
        if(!empty($res)){
            //存放用户
            session('user_info',$res->toArray());
            \app\home\controller\Cart::cookieToTable();
            $url=session('back_url')?:'/';
            $this->redirect($url);
        }else{
            $this->error('用户名或密码错误');
        }
        // 方法二
        // $info=User::where('phone',$param['username'])->whereOr('email',$param['username'])->whereOr('username',$param['username'])->find();
        // if($info && $info['password']=$param['password']){
        //     $this->redirect('index/index');
        // }else{
        //     $this->error('用户名或密码错误');
        // }
    }
//退出
       public function tuichu(){
        session(null);
        $this->redirect('home/login/login');
    }

}
